package com.example.moneygrosService.handlers;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;

import com.example.moneygrosService.MainActivityService.DB_TOKEN;
import com.example.moneygrosService.database.MoneyContract;
import com.example.moneygrosService.database.MoneyContract.UserProfiles;
import com.example.moneygrosService.database.MoneyContract.UserProfilesColumns;
import com.example.moneygrosService.User;

public class ModifyUserProfileHandler extends AsyncQueryHandler {
	private static final String TAG = "ModifyUserProfileHandler";
	
	private Bundle mBundle;
	private User mUser;
	private ContentResolver mCr;
	
	private boolean mUserInserted=false;
	private boolean mResult;
	
	private final Lock mLock = new ReentrantLock();
	private Condition mResultOKCond = mLock.newCondition();
	private boolean mResultOK;
	
	private ResultListener mListener;
	
//	public ModifyUserProfileHandler(ContentResolver cr, Bundle bundle) {
//		super(cr);
//		// TODO Auto-generated constructor stub
//		mCr= cr;
//		mBundle = bundle;
//		mUser = new User();
//		mUser.setUser_id(bundle.getString(UsersColumns.USER_ID));
//		mUser.setUser_name(bundle.getString(UsersColumns.USER_NAME));
//		mUser.setPhone_number(bundle.getString(UsersColumns.PHONE_NUMBER));
//		mUser.setBidirectional(bundle.getBoolean(UsersColumns.BIDIRECTIONAL,false));
//		mUser.setBalance(0);
//		mUser.setVersion("1.0");
//	}

	public ModifyUserProfileHandler(ContentResolver cr, User user) {
		super(cr);
		// TODO Auto-generated constructor stub
		mCr= cr;
		mUser = user;
	}
	
	public void modifyUserProfile(){
		CheckAndModifyUserProfileHandler checkAndModifyUserProfileHandler = new CheckAndModifyUserProfileHandler(mCr);
        checkAndModifyUserProfileHandler.checkAndModify();
	}


//	protected void userInserted(boolean insert){
//		mResultOK = true;
//		mResult = insert;
//		mUserInserted = insert;
//
//		if(mListener!=null)
//			mListener.onResult(insert, ResultType.USER_INSERTED, null);
//	}
//	
	public class CheckAndModifyUserProfileHandler extends AsyncQueryHandler {
		private static final String TAG = "CheckAndModifyUserProfileHandler";
		
		public CheckAndModifyUserProfileHandler(ContentResolver cr) {
			super(cr);
		}
		
		public void checkAndModify(){
			String[] projection = {BaseColumns._ID, UserProfilesColumns.USER_ID, UserProfilesColumns.USER_NAME, UserProfilesColumns.PHONE_NUMBER, UserProfilesColumns.VERSION};
			String selection = MoneyContract.UsersColumns.USER_ID+"=?";
			String[] selectionArgs= {mUser.getUser_id()};
			startQuery(DB_TOKEN.CHECK_USER_UPDATE_USER_PROFILE, (Object) mUser, UserProfiles.CONTENT_URI, projection, selection, selectionArgs, null);

		}


		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			// TODO Auto-generated method stub
			switch(token){
			case DB_TOKEN.CHECK_USER_UPDATE_USER_PROFILE:
				Log.v(TAG, "CHECK_USER_UPDATE_USER_PROFILE");
				if(cursor != null){
					User user = (User)cookie;
					if(cursor.getCount() != 0){
						//l'utilisateur existe!
						cursor.moveToFirst();

						Log.v(TAG, "update");
						user.setVersion(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.VERSION)));

						updateUserProfile(user);

					} else {
						//l'utilisateur n'existe pas!
						// l'insérer
						Log.v(TAG, "insert");
						user.setVersion("1.0");
						insertUserProfile(user);

					}

					cursor.close();
				}

				break;
			}
		}

		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#startQuery(int, java.lang.Object, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
		 */
		@Override
		public void startQuery(int token, Object cookie, Uri uri,
				String[] projection, String selection, String[] selectionArgs,
				String orderBy) {
			// TODO Auto-generated method stub
			super.startQuery(token, cookie, uri, projection, selection, selectionArgs,
					orderBy);
		}

		private void updateUserProfile(User user) {

			ContentValues values = new ContentValues();
			values.put(MoneyContract.UserProfilesColumns.USER_NAME, user.getUser_name());
			values.put(MoneyContract.UserProfilesColumns.VERSION, user.getVersion());
			values.put(MoneyContract.UserProfilesColumns.PHONE_NUMBER, user.getPhone_number());
			values.put(MoneyContract.UserProfilesColumns.BLUETOOTH_MAC, user.getBluetooth_MAC());
			String selection = MoneyContract.UsersColumns.USER_ID+"=?";
			String[] selectionArgs= {user.getUser_id()};
			startUpdate(DB_TOKEN.UPDATE_USER_PROFILE, user, UserProfiles.CONTENT_URI, values, selection, selectionArgs);
		}

		private void insertUserProfile(User user) {
	        ContentValues values = user.getProfileContentValues();
			startInsert(DB_TOKEN.INSERT_USER_PROFILE, (Object)user,UserProfiles.CONTENT_URI, values);

		}

	}


	/* (non-Javadoc)
	 * @see android.content.AsyncQueryHandler#onInsertComplete(int, java.lang.Object, android.net.Uri)
	 */
	@Override
	protected void onInsertComplete(int token, Object cookie, Uri uri) {
		switch(token){
		case DB_TOKEN.INSERT_USER_PROFILE:
			Log.v(TAG, "UserProfile "+((User)cookie).getUser_id()+" inserted.");

			break;
		}
	}

	/* (non-Javadoc)
	 * @see android.content.AsyncQueryHandler#onUpdateComplete(int, java.lang.Object, int)
	 */
	@Override
	protected void onUpdateComplete(int token, Object cookie, int result) {
		// TODO Auto-generated method stub
		switch(token){
		case DB_TOKEN.UPDATE_USER_PROFILE:
			Log.v(TAG, "UserProfile "+((User)cookie).getUser_id()+" updated.");

			break;
		}
	}

	
	
//
//	public void addResultListener(ResultListener obj) {
//		// TODO Auto-generated method stub
//		mListener = obj;		
//	}

}
